import { defineStore } from 'pinia';

export default defineStore('user', () => {
  const userInfo = ref<{
    open_id: string;
    union_id: string;
    user_id: string;
    avatar: string;
    nick_name: string;
    token: string;
  }>();

  const setUserInfo = (value: {
    open_id: string;
    union_id: string;
    user_id: string;
    avatar: string;
    nick_name: string;
    token: string;
  }) => {
    userInfo.value = value;
  };

  const clearUserInfo = () => {
    userInfo.value = undefined;
  };

  const isLogined = computed(() => userInfo.value !== undefined);

  // 一般这里要做token过期时间校验
  const getTokenAvailable = () => {
    if (!userInfo.value) return false;
    return true;
  };

  const getToken = () => {
    if (!userInfo.value) return '';
    return userInfo.value.token;
    // return `Bearer ${userInfo.value.token}`;
  };

  // 时间戳用于 watch 的监听
  const userAddress = ref<UniApp.ChooseAddressRes & { _t: number }>();
  const saveAddress = () => {
    uni.setStorageSync('user-address', JSON.stringify(userAddress.value));
  };
  const loadAddress = () => {
    const storage = uni.getStorageSync('user-address');
    try {
      userAddress.value = JSON.parse(storage) as UniApp.ChooseAddressRes & {
        _t: number;
      };
      if (!userAddress.value?.userName) {
        userAddress.value = undefined;
        uni.removeStorageSync('user-address');
      }
    } catch {
      userAddress.value = undefined;
    }
  };
  loadAddress();
  const getAddress = async () => {
    return new Promise((resolve) => {
      // #ifdef MP-ALIPAY
      uni.chooseAddress({
        success: (res) => {
          if (res.userName) {
            userAddress.value = { ...res, _t: Date.now() };
            saveAddress();
            resolve(true);
          } else {
            resolve(false);
          }
        },
        fail: (error) => {
          console.log('获取地址失败：');
          console.log(JSON.stringify(error));
          resolve(false);
        }
      });
      // #endif
      // #ifndef MP-ALIPAY
      uni.authorize({
        scope: 'scope.address',
        success: () => {
          uni.chooseAddress({
            success: (res) => {
              userAddress.value = { ...res, _t: Date.now() };
              saveAddress();
              resolve(true);
            },
            fail: (error) => {
              console.log('获取地址失败：');
              console.log(JSON.stringify(error));
              resolve(false);
            }
          });
        },
        fail: (error) => {
          console.log('授权失败：');
          console.log(JSON.stringify(error));
          resolve(false);
        }
      });
      // #endif
    });
  };
  const getRecipientInfo = () => {
    return {
      country: userAddress.value?.countyName || '',
      prov: userAddress.value?.provinceName || '',
      city: userAddress.value?.cityName || '',
      area: userAddress.value?.countyName || '',
      street: userAddress.value?.streetName || '',
      address: userAddress.value?.detailInfo || '',
      recipient: userAddress.value?.userName || '',
      mobile: userAddress.value?.telNumber || '',
      delivery_no: '',
      delivery_code: '',
      delivery_time: '',
      receive_time: '',
      logistics_content: '',
      update_delivery_code: true
    };
  };

  return {
    userInfo,
    setUserInfo,
    isLogined,
    clearUserInfo,
    getTokenAvailable,
    getToken,
    userAddress,
    getAddress,
    getRecipientInfo
  };
});
